package com.luych.toolbox.docker.service.job;

import com.luych.toolbox.common.enums.DockerRegistryStatus;
import com.luych.toolbox.common.enums.DockerServerStatus;
import com.luych.toolbox.common.event.base.service.publisher.WebSocketEventPublisher;
import com.luych.toolbox.common.event.base.service.publisher.WebSocketLetterPublisher;
import com.luych.toolbox.common.event.base.service.publisher.WebSocketNoticePublisher;
import com.luych.toolbox.common.feign.param.gateway.center.WebSocketEvent;
import com.luych.toolbox.docker.service.constant.Constant;
import com.luych.toolbox.docker.service.dao.DockerRegistryDao;
import com.luych.toolbox.docker.service.dao.DockerServerDao;
import com.luych.toolbox.docker.service.entity.DockerRegistry;
import com.luych.toolbox.docker.service.entity.DockerServer;
import com.luych.toolbox.docker.service.sdk.DockerClient;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.bus.BusProperties;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.List;

public class DockerRegistryHealthCheckJob extends QuartzJobBean {
    private static final Logger LOGGER = LoggerFactory.getLogger(DockerRegistryHealthCheckJob.class);

    private final BusProperties busProperties;
    private final ApplicationEventPublisher applicationEventPublisher;
    private final DockerServerDao dockerServerDao;
    private final DockerRegistryDao dockerRegistryDao;

    public DockerRegistryHealthCheckJob(BusProperties busProperties,
                                        ApplicationEventPublisher applicationEventPublisher,
                                        DockerServerDao dockerServerDao,
                                        DockerRegistryDao dockerRegistryDao) {
        this.busProperties = busProperties;
        this.applicationEventPublisher = applicationEventPublisher;
        this.dockerRegistryDao = dockerRegistryDao;
        this.dockerServerDao = dockerServerDao;
    }

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        String id = context.getJobDetail().getJobDataMap().getString("id");

        WebSocketLetterPublisher letterPublisher = new WebSocketLetterPublisher(busProperties, applicationEventPublisher);
        WebSocketNoticePublisher noticePublisher = new WebSocketNoticePublisher(busProperties, applicationEventPublisher);
        WebSocketEventPublisher eventPublisher = new WebSocketEventPublisher(busProperties, applicationEventPublisher);

        DockerRegistry dockerRegistry = dockerRegistryDao.findById(id).orElseThrow(() ->
                new JobExecutionException(Constant.DOCKER_REGISTRY_NOT_FOUND));



        DockerRegistryStatus status;
        LOGGER.info("start to check docker registry {} status...", dockerRegistry.getName());
        try {
            List<DockerServer> dockerServers = dockerServerDao.findByStatus(DockerServerStatus.NORMAL);
            if (dockerServers.isEmpty()) {
                status = DockerRegistryStatus.WAITING;
                LOGGER.info("docker registry {} connect unknown", dockerRegistry.getName());
            } else {
                DockerClient dockerClient = new DockerClient(dockerServers.get(0).getUrl());
                dockerClient.system().auth(dockerRegistry.getUser(), dockerRegistry.getPass(), dockerRegistry.getUrl());
                status = DockerRegistryStatus.NORMAL;
                LOGGER.info("docker registry {} connect success", dockerRegistry.getName());
            }
        } catch (Exception e) {
            LOGGER.error("docker registry {} connect error: {}", dockerRegistry.getName(), e.getMessage());
            status = DockerRegistryStatus.ABNORMAL;
        }
        if (!dockerRegistry.getStatus().equals(status)) {
            String message = "容器镜像仓库连接状态通知";
            if (dockerRegistry.getStatus() != DockerRegistryStatus.ABNORMAL && status == DockerRegistryStatus.ABNORMAL) {
                String content = "容器镜像仓库[" + dockerRegistry.getName() + "]连接异常，请注意修复！";
                letterPublisher.error(dockerRegistry.getOwnerId(), message, content);
                noticePublisher.error(dockerRegistry.getOwnerId(), content);
                eventPublisher.send(new WebSocketEvent(WebSocketEvent.Type.DOCKER_REGISTRY_ABNORMAL, dockerRegistry.getId()));
            } else if (dockerRegistry.getStatus() != DockerRegistryStatus.NORMAL && status == DockerRegistryStatus.NORMAL) {
                String content = "容器镜像仓库[" + dockerRegistry.getName() + "]连接正常。";
                letterPublisher.success(dockerRegistry.getOwnerId(), message, content);
                noticePublisher.success(dockerRegistry.getOwnerId(), content);
                eventPublisher.send(new WebSocketEvent(WebSocketEvent.Type.DOCKER_REGISTRY_NORMAL, dockerRegistry.getId()));
            }

            dockerRegistry.setStatus(status);
            dockerRegistryDao.save(dockerRegistry);
        }
    }
}
